/*My Web Server 
 *Bhojan Anand
 */

import java.util.*;

import java.io.*;
import java.net.*;



final class HttpRequestProcessor implements Runnable{

	Socket s;
	DataOutputStream dos;
	File f;
	String filename = ""; 
	Search_engine search_engine;
	String status="";
	

	//Constructor
	public HttpRequestProcessor(Socket socket, Search_engine search_engine) throws Exception 
	{
		// throws Exception here because don't want to deal
		// with errors in the rest of the code for simplicity.
		this.search_engine= search_engine;
		this.s = socket;


	}

	public void run() {
		try{
			processHttp();
		}catch (Exception ex){
			System.out.println(ex);
		}
	}	

	private void processHttp() throws Exception {

		// The next 3 lines create a buffer reader that
		// reads from the socket s.
		InputStream is = s.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);

		// The next 2 lines create a output stream we can
		// write to.
		OutputStream os = s.getOutputStream();
		dos = new DataOutputStream(os);

		// Read HTTP request (empty line signal end of request)
		String input = br.readLine();

		StringTokenizer st = new StringTokenizer(input);

		
		
		if (st.nextToken().equals("GET"))
		{
			// This is a GET request.  Parse filename.
			filename = st.nextToken();
			if (filename.startsWith("/")) 
			{
				filename = filename.substring(1);

			}
			

			if(filename.contains("?search_word"))
			{

				int beginIndex=filename.indexOf("=")+1;
				int endIndex= filename.indexOf("&");

				String search_term=filename.substring(beginIndex, endIndex);
				String encoded_search_term = new String(search_term);
				search_term=URLDecoder.decode(search_term, "UTF-8");
				search_term=search_term.trim();
				if(search_term.length()>0)
				{

					
						

		
					if(search_engine.set_search_term(search_term))
					{
						
						if(!search_engine.is_displayed())
						{
							filename="search_in_progress.html";
						}
						else
						{
							filename="search_result.html";
						}
					}
					else
					{
						filename="";
						status="Internet Connection Problem.";
					}


				}
				else
				{
					filename="";
					status="Please enter a word to search.";
				}

			}

			if(filename.length()==0)
			{
				filename="index.html";
				if(search_engine.is_running())
				{
					search_engine.stop();
					filename="search_result.html";
				}
			}

			filename = "Webfiles/" + filename; //my web folder
		}
		// read and throw away the rest of the HTTP request
		while (input.compareTo("") != 0) 
		{
			input = br.readLine();  //Just read and ignore
		}



		// Open and read the file into buffer
		f = new File(filename);

		if (f.canRead())
		{

			process_file();

		}
		else
		{
			// File cannot be read.  Reply with 404 error.
			dos.writeBytes("HTTP/1.0 404 Not Found\r\n");
			dos.writeBytes("\r\n");
			dos.writeBytes("Cannot find " + filename + " leh");
		}



		// Close connection (using HTTP 1.0 which is non-persistent).
		s.close();

	}

	private void process_file() throws IOException
	{
		//Create a File InputStrem to read the File


		if(filename.contains(".html"))
		{
			processhtml();



		}
		else
		{
			int size = (int)f.length();
			FileInputStream fis = new FileInputStream(filename);
			byte[] buffer = new byte[size];
			fis.read(buffer);
			dos.writeBytes("HTTP/1.0 200 Okie \r\n");
			dos.writeBytes("Content-type: text/html\r\n");
			dos.writeBytes("\r\n");
			dos.write(buffer,0,size);
		}
	}

	void processhtml() throws IOException
	{
		String content = new Scanner(f).useDelimiter("\\Z").next();


		if(filename.contains("search_in_progress.html"))
		{

			content = content.replace("$search_word",search_engine.get_search_term());
			content = content.replace("$search_website", search_engine.get_website_search());
		}
		
		
		if(filename.contains("index.html"))
		{

			content = content.replace("$status",status);
		}

		if(filename.contains("search_result.html"))
		{
			content = content.replace("$search_word", search_engine.get_search_term());
			content = content.replace("$num_result", String.valueOf(search_engine.get_num_result()));
			content = content.replace("$search_results", search_engine.get_search_result());
			content = content.replace("$num_url", String.valueOf(search_engine.get_num_url()));
			if(!search_engine.is_finished())
			content = content.replace("$Status", "<font color=\"red\"> Search is still in progress </font>");
			else
				content = content.replace("$Status", "<font color=\"green\"> Search has completed</font>");
				

		}
		
		if(filename.contains("statistics.html"))
		{
			content = content.replace("$TMSU", search_engine.get_top_most_search_url());
			content = content.replace("$THSK", search_engine.getTopTenMostSearchedKeyword());
			
			content = content.replace("$NOJI", String.valueOf(search_engine.getNumberOfJPEGImageFile()));
			content = content.replace("$NOPI", String.valueOf(search_engine.getNumberOfPNGImageFile()));
			content = content.replace("$NOGI", String.valueOf(search_engine.getNumberOfGifImageFile()));
			content = content.replace("$NOBI", String.valueOf(search_engine.getNumberOfBitmapImagefile()));
		}

		dos.writeBytes("HTTP/1.0 200 Okie \r\n");
		dos.writeBytes("Content-type: text/html\r\n");
		dos.writeBytes("\r\n");
		dos.writeBytes(content);
	}


}
